﻿using System;

namespace UniRx.Operators
{
	// Token: 0x020002AB RID: 683
	internal class FromEventPatternObservable<TDelegate, TEventArgs> : OperatorObservableBase<EventPattern<TEventArgs>> where TEventArgs : EventArgs
	{
		// Token: 0x06000EF4 RID: 3828 RVA: 0x00045DD8 File Offset: 0x000441D8
		public FromEventPatternObservable(Func<EventHandler<TEventArgs>, TDelegate> conversion, Action<TDelegate> addHandler, Action<TDelegate> removeHandler) : base(false)
		{
			this.conversion = conversion;
			this.addHandler = addHandler;
			this.removeHandler = removeHandler;
		}

		// Token: 0x06000EF5 RID: 3829 RVA: 0x00045DF8 File Offset: 0x000441F8
		protected override IDisposable SubscribeCore(IObserver<EventPattern<TEventArgs>> observer, IDisposable cancel)
		{
			FromEventPatternObservable<TDelegate, TEventArgs>.FromEventPattern fromEventPattern = new FromEventPatternObservable<TDelegate, TEventArgs>.FromEventPattern(this, observer);
			return (!fromEventPattern.Register()) ? Disposable.Empty : fromEventPattern;
		}

		// Token: 0x040008A5 RID: 2213
		private readonly Func<EventHandler<TEventArgs>, TDelegate> conversion;

		// Token: 0x040008A6 RID: 2214
		private readonly Action<TDelegate> addHandler;

		// Token: 0x040008A7 RID: 2215
		private readonly Action<TDelegate> removeHandler;

		// Token: 0x020002AC RID: 684
		private class FromEventPattern : IDisposable
		{
			// Token: 0x06000EF6 RID: 3830 RVA: 0x00045E23 File Offset: 0x00044223
			public FromEventPattern(FromEventPatternObservable<TDelegate, TEventArgs> parent, IObserver<EventPattern<TEventArgs>> observer)
			{
				this.parent = parent;
				this.observer = observer;
			}

			// Token: 0x06000EF7 RID: 3831 RVA: 0x00045E3C File Offset: 0x0004423C
			public bool Register()
			{
				this.handler = this.parent.conversion(new EventHandler<TEventArgs>(this.OnNext));
				try
				{
					this.parent.addHandler(this.handler);
				}
				catch (Exception error)
				{
					this.observer.OnError(error);
					return false;
				}
				return true;
			}

			// Token: 0x06000EF8 RID: 3832 RVA: 0x00045EB0 File Offset: 0x000442B0
			private void OnNext(object sender, TEventArgs eventArgs)
			{
				this.observer.OnNext(new EventPattern<TEventArgs>(sender, eventArgs));
			}

			// Token: 0x06000EF9 RID: 3833 RVA: 0x00045EC4 File Offset: 0x000442C4
			public void Dispose()
			{
				if (this.handler != null)
				{
					this.parent.removeHandler(this.handler);
					this.handler = default(TDelegate);
				}
			}

			// Token: 0x040008A8 RID: 2216
			private readonly FromEventPatternObservable<TDelegate, TEventArgs> parent;

			// Token: 0x040008A9 RID: 2217
			private readonly IObserver<EventPattern<TEventArgs>> observer;

			// Token: 0x040008AA RID: 2218
			private TDelegate handler;
		}
	}
}
